//
//  LGTPostDetailVC.swift
//  KJLGT
//
//  Created by jenkin on 2019/8/27.
//  Copyright © 2019年 jenkin. All rights reserved.
//

import UIKit
import SwiftyJSON
import WisdomHUD

enum DetailType:Int{
    case RWZ_PreView_Type = 0 //任务主 预览视图
    case RWZ_Task_Detail_Type = 1 //任务主 任务详情视图
    case RWZ_OrderView_Type = 2 //任务主 订单视图
    case LLZ_Task_Detail_Type = 3 //流量主 任务详情视图
    case LLZ_OrderView_Type = 4 //流量主 订单视图
}

class LGTPostDetailVC: LGTBaseVC, UITableViewDelegate, UITableViewDataSource, PhotoDelegate{
//    var isRWZ:Bool = true // 是不是任务主  false流量主
//    var isOrderView:Bool = false // 是不是订单视图
//    var isPreview:Bool = true  //默认是预览的
    
    var photoManager:PhotoManager? = {
        let photoManagr1 = PhotoManager()
        return photoManagr1
    }()
    
    var cellRetunrStrBlock:ClickCellStrBlock?  //键盘文字变化回掉处理
    var updateOrderBlock:ClickInfoBlock? //返回订单详情
    var viewDetailType:DetailType = .RWZ_PreView_Type //视图类型
    var is_isset:Int = 0 //是不是接单 1是
    var stepCellClickBlock:ClickStepPathBlock? //步骤点击返回处理
    var topParam:Dictionary<String, Any>?
    var userModel:UserModel? = UserModel.share
    var moreView:UIView?
    var footMoreView:UIView?
    //任务请求参数
    var taskModel:TaskModel?
    //订单详情请求参数
    var orderModel:TaskOrderModel?
    //任务主 订单状态是待提交的状态可以编辑
    var canEdit:Bool = false
    //当前上传图片的路径
    var currentUploadImagePath:IndexPath?
    //存储提交订单的数据
    var orderSubmitInfo:Dictionary<String, Any> = [:]
    //参数保存
    var submitDataInfo2:Dictionary<String, Any?> = [:]
    var tableView:UITableView?
    var data:Array<Array<Dictionary<String, Any?>>> = Array.init()
    //订单参数
    var taskDetailInfo:Dictionary<String, Any> = [:]
    var infoData:Dictionary<String, Any> = [:]
    var clickBlock:ClickIndexBlock?
    //操作记录
    var timeStepArray:Array<Dictionary<String, Any>>?
    var footerView:UIView?
    var stepArray:Array<Dictionary<String, Any>> = []
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setBlock()
        self.getData()
        NotificationCenter.default.addObserver(self, selector: #selector(paySuccessAction), name: Pay_Success_Note, object: nil)
    }

    @objc func paySuccessAction(){
        self.getData()
    }

    deinit {
        NotificationCenter.default.removeObserver(self, name: Pay_Success_Note, object: nil)
    }
    
    func setBlock(){
        weak var weakSelf = self
        self.updateOrderBlock = {(index:Int, info:Dictionary<String, Any>) in
            weakSelf?.dataChange(json: info)
        }
        
        self.reloadBlock = { () in
            weakSelf?.getData()
        }
        
        //操作记录
        self.clickBlock = {(index:Int) in
            let vc:LGTRWZOperateRecodeVC = LGTRWZOperateRecodeVC()
            vc.data = weakSelf?.timeStepArray ?? []
            weakSelf?.navigationController?.pushViewController(vc, animated: true)
        }
        
        //步骤上的cell 点击
        self.stepCellClickBlock = {(data:Dictionary<String, Any>, path:IndexPath,  index:Int) -> Void in
            let row:Int = path.row - 1
            var reloadState:Bool = true
            switch index {
            case StepCellClickType.openurl.rawValue: //打开链接
                let url:String = data["subText"] as? String ?? ""
                let gotoURL:URL? = URL.init(string: url)
                if gotoURL != nil{
                    UIApplication.shared.open(gotoURL!, options: [:], completionHandler: nil)
                }
                reloadState = false
                break
            //复制数据
            case StepCellClickType.copydata.rawValue:
                let url:String = data["subText"] as? String ?? ""
                UIPasteboard.general.string = url
                WisdomHUD.showSuccess(text: "复制成功")
                reloadState = false
                break
            case StepCellClickType.copyurl.rawValue: //复制链接
                let url:String = data["subText"] as? String ?? ""
                UIPasteboard.general.string = url
                WisdomHUD.showSuccess(text: "复制成功")
                reloadState = false
                break
                
                //上传图片
            case StepCellClickType.addCheckImage.rawValue:
                print("上传图片")
                weakSelf?.addImageAction()
                weakSelf?.currentUploadImagePath = path
                break;
            default:
                break
            }
        }
        
        //cell返回字符串
        self.cellRetunrStrBlock = { (data:String, path:IndexPath) -> Void in
            let key:String = "\(path.row)"
            weakSelf?.orderSubmitInfo[key] = data
            weakSelf?.initData(reload: false)
        }
    }
    
    override func setUI() {
        super.setUI()
        
        var title:String = "任务详情"
        if self.viewDetailType == .LLZ_OrderView_Type || self.viewDetailType == .LLZ_OrderView_Type{
            title = "订单详情"
        }
        
        self.setBavBarStyle(navBarHiden: false, title: title, back: true)
        self.tableView = UITableView.init(frame: CGRect.init(x: 0.0, y: NavBarH, width: Double(KScreenW), height: Double(KScreenH) - NavBarH - TabBarH), style: UITableView.Style.plain)
        self.view.addSubview(self.tableView!)
        self.tableView?.backgroundColor = ViewBackColor
        self.tableView?.separatorStyle = UITableViewCell.SeparatorStyle.none
        self.tableView?.delegate = self as UITableViewDelegate
        self.tableView?.dataSource = self as UITableViewDataSource
        self.tableView?.register(LGTRWZPostDetailUrlStepCell.classForCoder(), forCellReuseIdentifier: "urlCell")
        self.tableView?.register(LGTRWZPostDetailCopyStepCell.classForCoder(), forCellReuseIdentifier: "copyCell")
        self.tableView?.register(LGTRWZPostDetailImageTextStepCell.classForCoder(), forCellReuseIdentifier: "imagetextcell")
        self.tableView?.register(LGTStepTitleViewCell.classForCoder(), forCellReuseIdentifier: "stepHeadCell")
        self.tableView?.register(LGTPostDetailTitleViewCell.classForCoder(), forCellReuseIdentifier: "titleCell")
        self.tableView?.register(LGTPostDetailTaskInfoViewCell.classForCoder(), forCellReuseIdentifier: "taskInfoCell")
        self.tableView?.register(LGTPostDetailRequestViewCell.classForCoder(), forCellReuseIdentifier: "requestCel")
        self.tableView?.register(LGTRWZPostTopViewCell.classForCoder(), forCellReuseIdentifier: "topCell")
        self.tableView?.register(LGTRWZPostOrderViewCell.classForCoder(), forCellReuseIdentifier: "orderCell")
        self.tableView?.register(LGTRWZPostSelectCell.classForCoder(), forCellReuseIdentifier: "selectCell")
        
        
//        tableView?.contentInset =
//            UIEdgeInsets.init(top: 0.0, left: 0.0, bottom: TabBarH, right: 0.0)
        self.tableView?.estimatedRowHeight = 40
        self.tableView?.rowHeight = UITableView.automaticDimension
        
        let moreBtn:UIButton = LGTViewCreateUtil.share.createTextLGTButton(title: "", font: Font_Bold_18, color: UIColor.clear, selectedColor: UIColor.clear, dW: SizeFitFloat(10), dH: SizeFitFloat(10))
        moreBtn.setImage(UIImage.init(named: "more_icon_pic"), for: UIControl.State.normal)
        moreBtn.setImage(UIImage.init(named: "more_icon_pic"), for: UIControl.State.selected)
        self.navBar.addSubview(moreBtn)
        moreBtn.snp.makeConstraints { (make) in
            make.right.equalTo(-SizeFitFloat(12))
            make.width.equalTo(SizeFitFloat(22))
            make.height.equalTo(SizeFitFloat(4))
            make.bottom.equalTo(-SizeFitFloat(19))
        }
        moreBtn.addTarget(self, action: #selector(moreAction), for: UIControl.Event.touchUpInside)
        tableView?.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: -SizeFitFloat(8), right: 0)
        self.view.backgroundColor = ViewBackColor
        self.footerView = UIView.init()
        self.footerView?.isHidden = true
        self.footerView?.backgroundColor = UIColor.white
        self.view.addSubview(self.footerView!)
        self.footerView!.snp.makeConstraints { (make) in
            make.bottom.left.equalTo(0)
            make.height.equalTo(TabBarH)
            make.width.equalTo(self.view)
        }
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.data.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let array = self.data[section]
        return array.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let array:Array<Dictionary<String, Any>> = self.data[indexPath.section]
        let info = array[indexPath.row]
        let collection:Bool = info["collection"] as? Bool ?? false
        let copy:Bool = info["copy"] as? Bool ?? false
        let isurl:Bool = info["isurl"] as? Bool ?? false
        let imageAndText:Bool = info["imageAndText"] as? Bool ?? false
        let stepHead:Bool = info["stepHead"] as? Bool ?? false
        let isUserInfo:Bool = info["isUserInfo"] as? Bool ?? false
        let isRequest:Bool = info["isRequest"] as? Bool ?? false
        let isTaskInfo:Bool = info["isTaskInfo"] as? Bool ?? false
        let isTop:Bool = info["isTop"] as? Bool ?? false
        let isOrder:Bool = info["isOrder"] as? Bool ?? false
        
        //orderCell
        if isOrder == true{
            let cell:LGTRWZPostOrderViewCell = tableView.dequeueReusableCell(withIdentifier: "orderCell", for: indexPath) as! LGTRWZPostOrderViewCell
            cell.model = self.taskDetailInfo
            cell.clickBlock = self.clickBlock
            return cell
        }
        else if isTop == true{
            let cell:LGTRWZPostTopViewCell = tableView.dequeueReusableCell(withIdentifier: "topCell", for: indexPath) as! LGTRWZPostTopViewCell
            cell.model = info
            cell.clickBlock = self.clickBlock
            return cell
        }
        if isUserInfo == true{
            let cell:LGTPostDetailTitleViewCell = tableView.dequeueReusableCell(withIdentifier: "titleCell", for: indexPath) as! LGTPostDetailTitleViewCell
             cell.model = info
            return cell
        }else if isRequest == true{
            let cell:LGTPostDetailRequestViewCell = tableView.dequeueReusableCell(withIdentifier: "requestCel", for: indexPath) as! LGTPostDetailRequestViewCell
             cell.model = info
            return cell
        }else if isTaskInfo == true{
            let cell:LGTPostDetailTaskInfoViewCell = tableView.dequeueReusableCell(withIdentifier: "taskInfoCell", for: indexPath) as! LGTPostDetailTaskInfoViewCell
             cell.model = info
            return cell
        }
        //复制 和 收集
        else if collection == true || copy == true{
            let cell:LGTRWZPostDetailCopyStepCell = tableView.dequeueReusableCell(withIdentifier: "copyCell", for: indexPath) as! LGTRWZPostDetailCopyStepCell
            cell.path = indexPath
            cell.stepCellClickBlock = self.stepCellClickBlock
            cell.returnStrBlock = self.cellRetunrStrBlock
            cell.model = info
            return cell
        }
            //打开url
        else if isurl == true{
            let cell:LGTRWZPostDetailUrlStepCell = tableView.dequeueReusableCell(withIdentifier: "urlCell", for: indexPath) as! LGTRWZPostDetailUrlStepCell
            cell.path = indexPath
            cell.model = info
            cell.stepCellClickBlock = self.stepCellClickBlock
            return cell
        }
            //图片
        else if imageAndText == true{
            let cell:LGTRWZPostDetailImageTextStepCell = tableView.dequeueReusableCell(withIdentifier: "imagetextcell", for: indexPath) as! LGTRWZPostDetailImageTextStepCell
            cell.path = indexPath
            cell.model = info
            cell.stepCellClickBlock = self.stepCellClickBlock
            return cell
        }
            //操作步骤头部
        else if stepHead == true{
            let cell:LGTStepTitleViewCell = tableView.dequeueReusableCell(withIdentifier: "stepHeadCell", for: indexPath) as! LGTStepTitleViewCell
            return cell
        }
        else{
            let cell:LGTRWZPostSelectCell = tableView.dequeueReusableCell(withIdentifier: "selectCell", for: indexPath) as! LGTRWZPostSelectCell
            cell.model = info
            return cell
        }
    }
    
    //获取数据
    func getData(){
//        //预览
//        if self.isPreview == true{
//            self.initData()
//            return
//        }
        //预览  从外部传数据过来
        if self.viewDetailType == .RWZ_PreView_Type{
            self.initData()
            return
        }
        
        var param:Dictionary<String, Any> = [:]
        if self.viewDetailType == .LLZ_Task_Detail_Type || self.viewDetailType == .RWZ_Task_Detail_Type{
            if self.taskModel == nil{
                return
            }
            let id:Int = self.taskModel!.id ?? 0
            param["id"] = id
        }
        if self.viewDetailType == .LLZ_OrderView_Type || self.viewDetailType == .RWZ_OrderView_Type{
            if self.orderModel == nil{
                return
            }
            let id:Int = self.orderModel!.id ?? 0
            param["id"] = id
        }
//        case RWZ_Task_Detail_Type = 1 //任务主 任务详情视图
//        case RWZ_OrderView_Type = 2 //任务主 订单视图
//        case LLZ_Task_Detail_Type = 3 //流量主 任务详情视图
//        case LLZ_OrderView_Type = 4 //流量主 订单视图
        
        //获取订单详情
        weak var weakSelf = self
        
        var url:String = Task_Detail_URL
        if self.viewDetailType == .RWZ_Task_Detail_Type{
            
        }else if self.viewDetailType == .LLZ_Task_Detail_Type{
            url = LLZ_Task_Detail_URL
        }else if self.viewDetailType == .LLZ_OrderView_Type{
            url = LLZ_Order_Detail_URL
        }else if self.viewDetailType == .RWZ_OrderView_Type{
            url = Task_OrderDetail_URL
        }
        LGTHttpUtil.httpUtil.requestData(url: url, param: param, success: { (json) in
            //let data:Dictionary<String, Any> = json["data"] as? Dictionary<String, Any> ?? [:]
            weakSelf?.dataChange(json: json)
        }) { (json) in
             weakSelf?.showNoData(image: Net_NoData_Image, text: Net_Error_Text, subText: Net_Reload_Text)
        }
    }
    
    //数据转换
    func dataChange(json:Dictionary<String, Any>){
        self.canEdit = false
        var jsonInfo:Dictionary<String, Any> = json
        //订单数据需要转换
        if self.viewDetailType == .LLZ_OrderView_Type || self.viewDetailType == .RWZ_OrderView_Type{
            var data:Dictionary<String, Any> = json["data"] as? Dictionary<String, Any> ?? [:]
            var taskInfo:Dictionary<String, Any> = data["task"] as? Dictionary<String, Any> ?? [:]
            taskInfo["params"] = data["params"]
            jsonInfo["data"] = taskInfo
            let status:Int = data["status"] as? Int ?? 0
            self.taskDetailInfo = ["status":status, "expire_time":data["expire_time"]]
            if status == 1 && self.viewDetailType == .LLZ_OrderView_Type{
                self.canEdit = true
            }
        }

        self.taskInfoChangeSubmitInfo(json: jsonInfo)
        //数据初始化
        self.initData()
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view:UIView = UIView.init()
        view.backgroundColor = ViewBackColor
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if section == self.data.count - 1{
            return SizeFitFloat(1)
        }
        return SizeFitFloat(8)
    }
    
    @objc func moreAction(){
        
        if self.moreView == nil{
            self.moreView = UIView.init()
            self.moreView?.backgroundColor = UIColor.white
            self.moreView?.layer.borderColor = GrayColor.cgColor
            self.moreView?.layer.borderWidth = 1
            self.view.addSubview(self.moreView!)
            self.moreView?.isHidden = true
            self.moreView?.snp.makeConstraints({ (make) in
                make.width.equalTo(SizeFitFloat(100))
                make.height.equalTo(SizeFitFloat(81))
                make.top.equalTo(NavBarH)
                make.right.equalTo(-SizeFitFloat(9))
            })
            
            let  gerOrderDescBtn:LGTButton = LGTViewCreateUtil.share.createTextLGTButton(title: "接单声明", font: Font_Normal_18, color: TextColor, selectedColor: TextColor, dH: SizeFitFloat(5))
            self.moreView?.addSubview(gerOrderDescBtn)
            gerOrderDescBtn.snp.makeConstraints { (make) in
                make.left.right.equalTo(0)
                make.top.equalTo(SizeFitFloat(12))
                make.height.equalTo(SizeFitFloat(20))
            }
            
            let  freeDesc:LGTButton = LGTViewCreateUtil.share.createTextLGTButton(title: "免责声明", font: Font_Normal_18, color: TextColor, selectedColor: TextColor, dH: SizeFitFloat(5))
            self.moreView?.addSubview(freeDesc)
            freeDesc.snp.makeConstraints { (make) in
                make.left.right.equalTo(0)
                make.top.equalTo(SizeFitFloat(48))
                make.height.equalTo(SizeFitFloat(20))
            }
        }
        
        self.moreView?.isHidden = !self.moreView!.isHidden
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        self.moreView?.isHidden = true
        self.footMoreView?.isHidden = true 
    }
    
    @objc func addImageAction(){
        self.photoManager?.unNeedCrop = true
        self.photoManager?.delegate = self as PhotoDelegate
        let alertVC = UIAlertController.init(title: "获取方式", message: "", preferredStyle: UIAlertController.Style.actionSheet)
        weak var weakSelf = self
        let playAction = UIAlertAction.init(title: "拍照", style: UIAlertAction.Style.default) { (action) in
            weakSelf?.photoManager?.actionSheet(UIActionSheet(), clickedButtonAt: 0)
        }
        let ablumAction = UIAlertAction.init(title: "从相册中选择", style: UIAlertAction.Style.default) { (action) in
            weakSelf?.photoManager?.actionSheet(UIActionSheet(), clickedButtonAt: 1)
        }
        let cancelAction = UIAlertAction.init(title: "取消", style: UIAlertAction.Style.cancel) { (action) in
            
        }
        alertVC.addAction(playAction)
        alertVC.addAction(ablumAction)
        alertVC.addAction(cancelAction)
        self.present(alertVC, animated: true, completion: nil)
    }
    
    //裁剪图片代理
    func imageCropper(_ cropperViewController: VPImageCropperViewController!, didFinished editedImage: UIImage!) {
        if self.currentUploadImagePath == nil{
            return
        }
        
        let image:UIImage = LGTOCBaseUtil.compressOriginalImage(editedImage, to: CGSize.init(width: 600, height: 600))
        let data:Data = image.jpegData(compressionQuality: 1) ?? Data()
        let param:Dictionary<String, Any> = ["image":data]
        weak var weakSelf = self
        WisdomHUD.showLoading(text: "上传图片中...")
        LGTHttpUtil.httpUtil.uploadData(url: Upload_Image_URL, param: param, showMessage: true, success: { (json) in
            let info:Dictionary<String, Any> = json["data"] as? Dictionary<String, Any> ?? [:]
            let key:String = "\(weakSelf?.currentUploadImagePath?.row as? Int ?? 0)"
            weakSelf?.orderSubmitInfo[key] = info
            weakSelf?.initData()
        }) { (json) in
            
        }
        if cropperViewController != nil{
            cropperViewController.dismiss(animated: true, completion: nil)
        }
    }
    
    func imageCropperDidCancel(_ cropperViewController: VPImageCropperViewController!) {
        cropperViewController.dismiss(animated: true, completion: nil)
    }
    
    func finish(_ controller: UIViewController!) {
        self.present(controller, animated: true, completion: nil)
    }
    
    func getCropSize() -> CGRect {
        return CGRect.init(x: 0, y: (KScreenH - KScreenW)/2, width: KScreenW, height: KScreenW)
    }
}
